<?php
namespace Particle\Apps;
use Particle\Core as Core;
/**
 * Load settings from file settings.xml
 * The configuration file defines: 
 * - The files (PHP, JS, Smarty) which must include the host.
 * - The files (PHP, JS, Smarty) to be included in any host.
 * 
 * @package Particle
 * @category Apps
 * @author dertin
 * @todo Falta agregar carga de archivos CSS
 *  
 **/
final class Settings{

    private $_flagLoadSettings = FALSE;
    private $_xmlSettingsSite = NULL;
    private $_xmlSettingsGlobal = NULL;
    private $_aFilesPHP = NULL;
    private $_aFilesJS = NULL;
    private $_aFileSmarty = NULL;
    private $_sConfDirSmarty = NULL;
    
    /**
    * @staticvar object Instance of class
    */
    private static $instance = NULL;
    
    /**
    * Singleton
    * @return object|bool If previously not start the instance in conjunction with the method (initSettings), the result is false.
    * @static
    */
    public static function getInstance()
    {
        if ( is_null( self::$instance ) )
        {
            self::$instance = new self();
        }else{
            if(self::$instance->_flagLoadSettings == false){
                return false;
            }
        }
        return self::$instance;
        
    }
    /**
     * It is stored in the attributes of the class:
     * - The configuration from the XML file.
     * This method should be invoked with the instance of the method (getInstance)
     * @access public
     * @example Apps\Settings::getInstance()->initSettings();
     */
    public function initSettings() 
    {
        $this->loadSettings( $this->xmlSettings() ); 
    }
    
    private final function xmlSettings() 
    {
        $this->_flagLoadSettings = TRUE;
        
        if(SETTINGS_PATH == FALSE){
            $this->_flagLoadSettings = TRUE;
            return FALSE;
        }
        
        if (is_readable(SETTINGS_PATH))
        {
            
            $simplexml_load_file = simplexml_load_file(SETTINGS_PATH);
            
            if(!isset($simplexml_load_file) || $simplexml_load_file == FALSE){
                throw new \Exception ('Error Load XML Settings');
            }
            
            $xmlData = json_decode(json_encode((array) $simplexml_load_file), 1);  
            
            if(isset($xmlData) && !is_null($xmlData) && !empty($xmlData))
            {
                
                return $xmlData;
                
            } else {
                
                $this->_flagLoadSettings = FALSE;
                return FALSE;
                
            }
            
        } else {
            
            $this->_flagLoadSettings = FALSE;
            throw new \Exception ('Error File Settings');
        }
    }
    
    private final function loadSettingX($settingFiles, $ext, $settingDir = '', $aHosts = ''){
                
        if(empty($aHosts)){
            $aHosts = Core\Security::filterXSS($_SERVER['HTTP_HOST']);
        }
        
        if(isset($settingFiles)){
            
            if($ext == 'dirsmarty'){
                $tempPathSmarty = APPS_CONST_PATH.$settingDir.DS.(string)$settingFiles.DS;
                 
                if(!is_dir($tempPathSmarty)){
                    $this->_flagLoadSettings = FALSE;
                    throw new \Exception ('Error DirConfSmarty');
                }
                
                $this->_sConfDirSmarty = $tempPathSmarty;
                
                return true;
            }
            
            $countFilephp = count($settingFiles);

            if(!is_array($settingFiles))
            {
                $tempArray = array();
                $tempArray[] = (string)$settingFiles;
                unset($settingFiles);
                $settingFiles = $tempArray;
                unset($tempArray);
            }
            
            for ($f = 0; $f < $countFilephp; $f++)
            {
                    if($ext == '.php'){
                        
                        $tempPathFile = APPS_CONST_PATH.$settingDir.DS.$settingFiles[$f].$ext;
                        if(is_file($tempPathFile)){
                            $this->_aFilesPHP[] = $tempPathFile;
                        }
                        
                    }elseif ($ext == '.js'){
                        
                        $protocolo = '';
                        if( defined('HTTPS') && HTTPS == TRUE ){
                            $protocolo = "https://";
                        }else{
                            $protocolo = "http://";
                        }
                        
                        $aExtraPath = '';
                        if(defined('installationFolder')){
                            $aExtraPath = installationFolder;
                        }
                        
                        $tempPathFile = $protocolo.$aHosts.$aExtraPath.'/'.APPS_CONST_REL.$settingDir.'/'.$settingFiles[$f].$ext;
                        if(isset($tempPathFile) && !empty($tempPathFile)){
                            $this->_aFilesJS[] = $tempPathFile;
                        }
                        
                    }elseif($ext == '.conf'){
                                  
                        $tempPathFile = APPS_CONST_PATH.$settingDir.DS.$settingFiles[$f].$ext;
                        if(is_file($tempPathFile)){
                            $this->_aFileSmarty[] = $tempPathFile;
                        }
                    }
                
                unset($tempPathFile);                                
            }
            
            return true;
        
        }else{
            return false;
        }
        
    }

        
    private final function loadSettings($xmlSettings = FALSE)
    {
        if(!isset($xmlSettings) || $xmlSettings == FALSE || count($xmlSettings) <= 0 || !is_array($xmlSettings) || !$this->_flagLoadSettings)
        {
            $this->_flagLoadSettings = FALSE;
            return FALSE;
        }
        else
        {
            // GLOBAL SETTINGS
            if(isset($xmlSettings['global']) && count($xmlSettings['global']) > 0 && is_array($xmlSettings['global'])){
                
                $this->_xmlSettingsGlobal = $xmlSettings['global'];
                
                if(isset($this->_xmlSettingsGlobal['@attributes']['folder']) && is_string($this->_xmlSettingsGlobal['@attributes']['folder']))
                {
                    $tempGlobalDir = $this->_xmlSettingsGlobal['@attributes']['folder'];
                    
                    if(isset($this->_xmlSettingsGlobal['filephp'])){
                        $this->loadSettingX($this->_xmlSettingsGlobal['filephp'], '.php', $tempGlobalDir);
                    }
                    if(isset($this->_xmlSettingsGlobal['filejs'])){
                        $this->loadSettingX($this->_xmlSettingsGlobal['filejs'], '.js', $tempGlobalDir);
                    }
                    if(isset($this->_xmlSettingsGlobal['dirsmarty'])){
                        $this->loadSettingX($this->_xmlSettingsGlobal['dirsmarty'], 'dirsmarty', $tempGlobalDir);
                    }
                    if(isset($this->_xmlSettingsGlobal['filesmarty'])){
                        $this->loadSettingX($this->_xmlSettingsGlobal['filesmarty'], '.conf', $tempGlobalDir);
                    }
                }
                
                $this->_flagLoadSettings = TRUE;
            }
            
            // HOST SETTINGS
            if(isset($xmlSettings['sites']['site']) && count($xmlSettings['sites']['site']) > 0 && is_array($xmlSettings['sites']['site'])){
                
                $this->_xmlSettingsSite = $xmlSettings['sites']['site'];
            
            
                if(isset($this->_xmlSettingsSite['@attributes']) && is_array($this->_xmlSettingsSite['@attributes']))
                {
                    $this->_xmlSettingsSite[0] = $this->_xmlSettingsSite;
                    unset($this->_xmlSettingsSite['@attributes']);
                    unset($this->_xmlSettingsSite['httphost']);
                    unset($this->_xmlSettingsSite['filephp']);
                    unset($this->_xmlSettingsSite['filejs']);
                    unset($this->_xmlSettingsSite['filesmarty']);
                    unset($this->_xmlSettingsSite['comment']);
                }

                $countXmlSettings = count($this->_xmlSettingsSite);

                for ($i = 0; $i < $countXmlSettings; $i++)
                {
                    unset($this->_xmlSettingsSite[$i]['comment']);
                    
                    $splitter = '|';
                    if(isset($this->_xmlSettingsSite[$i]['@attributes']['splitter'])){
                        $splitter = $this->_xmlSettingsSite[$i]['@attributes']['splitter'];
                    }
                    
                    if(!isset($this->_xmlSettingsSite[$i]['httphost'])){
                        
                        $this->_flagLoadSettings = FALSE;
                        throw new \Exception ('Error need to define httphost');
                        
                    }
                    
                    $aHosts = preg_split('/\\'.$splitter.'/', $this->_xmlSettingsSite[$i]['httphost']); 
                    
                    $countHosts = count($aHosts);
                    
                    for ($a = 0; $a < $countHosts; $a++)
                    {
                        if ($_SERVER['HTTP_HOST'] == $aHosts[$a]){
                            
                            $folder = '';
                            if(isset($this->_xmlSettingsSite[$i]['@attributes']['folder']) && is_string($this->_xmlSettingsSite[$i]['@attributes']['folder'])){
                                $folder = $this->_xmlSettingsSite[$i]['@attributes']['folder'];
                            }
                            if(isset($this->_xmlSettingsSite[$i]['filephp'])){
                                $this->loadSettingX($this->_xmlSettingsSite[$i]['filephp'], '.php', $folder);
                            }
                            if(isset($this->_xmlSettingsSite[$i]['filejs'])){
                                $this->loadSettingX($this->_xmlSettingsSite[$i]['filejs'], '.js', $folder);
                            }
                            if(isset($this->_xmlSettingsSite[$i]['dirsmarty'])){
                                $this->loadSettingX($this->_xmlSettingsSite[$i]['dirsmarty'], 'dirsmarty', $folder);
                            }
                            if($this->_xmlSettingsSite[$i]['filesmarty']){
                                $this->loadSettingX($this->_xmlSettingsSite[$i]['filesmarty'], '.conf', $folder);
                            }
                        }
                    }
                }
                
                $this->_flagLoadSettings = TRUE;
            }
        }
        
    }
    
    public final  function getSettingsFilephp(){
        return $this->_aFilesPHP;
    }
    public final  function getSettingsFilejs(){
        return $this->_aFilesJS;
    }
    public final  function getSettingsFilesmarty(){
        return $this->_aFileSmarty;
    }
    public final  function getSettingsConfDirSmarty(){
        return $this->_sConfDirSmarty;
    }
    
}